import Ember from 'ember';
import _ from 'lodash/lodash';
import config from '../../config/environment';

export default Ember.Route.extend({

  beforeModel: function(transition){
    var _self = this;
    var router = App.lookup('router:main');
    //处理路由映射数据
    var routeNames = router.router.recognizer.names;
    console.log("routeNames is",routeNames);
    //在这里阻塞方式处理当前任务，保证下面的页面能拿到数据
    return new Ember.RSVP.Promise(function (resolve, reject) {
      console.log("beforeModel in mainpage");
      _self.processTaskInfo().then(function(){
        _self.refreshTaskMenu();
        resolve();
      },function(){
        resolve();
      });
    });
  },

  model(params,transition) {
    return new Ember.RSVP.hash({
      routeList: new Ember.A(),
      curTask: this.get("global_curStatus").getTask(),
      otherTasks: this.get("global_curStatus").getOtherTasks(),
    });
  },

  //处理当前任务
  processTaskInfo: function(){
    var _self = this;
    //设置顶部任务条上的任务信息
    var curStatus = this.get("global_curStatus");
    var curUser = curStatus.getUser();
    //客服对应usertask企业对应task
    console.log("is cs",curUser.get("isCustomerService"));
    var filter = null;
    var index = 0;
    var len = 0;
    return new Ember.RSVP.Promise(function (resolve, reject) {
      if(curUser.get("isCustomerService")){
        filter = {
          user:{id:curUser.get("id")},
          status:{typecode:Constants.taskApplyStatus_applySuc},
          task:{
              'status---1':{'typecode@$or1---1':Constants.taskStatus_begin},
              'status---2':{'typecode@$or1---2':Constants.taskStatus_isPassed},
          }
        };
        _self.store.query("userTask",{filter:filter}).then(function(userTasks){
          len = userTasks.get("length");
          if(len===0){
            resolve();
            return;
          }
          //设置到全局变量
          curStatus.setTasks(userTasks);
          userTasks.forEach(function(userTask){
            index++;
            console.log("usertask id:" + userTask.get('task.id') + " and currentTask id:" + curUser.get("currentTask").get("id"));
            if(userTask.get('task.id') === curUser.get("currentTask").get("id")){
              console.log("need set task:");
              curStatus.setTask(userTask);
            }
            if(len<=index){
              console.log("need res main");
              resolve();
            }
          });
        });
      }else{
        filter = {pubuser:{id:curUser.get("id")},
          'status---1':{'typecode@$or1---1':Constants.taskStatus_begin},
          'status---2':{'typecode@$or1---2':Constants.taskStatus_isPassed},
        };
        _self.store.query("task",{filter:filter}).then(function(taskList){
          len = taskList.get("length");
          if(len===0){
            resolve();
            return;
          }
          //设置到全局变量
          curStatus.setTasks(taskList);
          taskList.forEach(function(task){
            index++;
            //去掉当前任务，得到其他的任务
            if(task.get('id') === curUser.get("currentTask").get("id")){
              curStatus.setTask(task);
            }
            if(len<=index){
              resolve();
            }
          });
        });
      }
    });
  },
  setupController: function(controller, model){
    console.log("setupController in mainpage");
    this._super(controller, model);
    controller.setProperties(model);
    this.set("controller",controller);
  },
  //阻止下级页面直接访问
  afterModel: function(model,transition) {
    return;
    var routeHome = "cs-home";
    var curUser = this.get("global_curStatus").getUser();
    //意味着刷新后跳转到主页面
    if(this.get("global_curStatus").get("isMobile")){
      routeHome = "task-square";
      if(config.host==="http://api.callcloud.cn"&&false){
	      transition.abort();
	      return;
      }else{
        // return;
      }
    }
    console.log("afterModel in,routeHome:" + routeHome);
    this.controllerFor("business.mainpage").switchMainPage(routeHome);
  },
  //刷新任务下拉菜单显示
  refreshTaskMenu: function() {
    //TODO
  },
  actions:{
    saveRefresh(){
      var _self = this;
      var currentRouteName = Ember.getOwner(_self).lookup('controller:application').currentPath;
      if(currentRouteName&&CommonUtil.Common_endsWith(currentRouteName,".index")){
        console.log("need cut .index");
        currentRouteName = currentRouteName.substr(0,currentRouteName.length-6);
      }
      var currentRouteInstance = Ember.getOwner(_self).lookup('route:' + currentRouteName);
      console.log("currentRouteName:" + currentRouteName);
      //修改全局任务数据
      _self.processTaskInfo().then(function(){
        console.log("do refresh");
        _self.refreshTaskMenu();
        //刷新下级页面
        currentRouteInstance.refresh();
      });
    },
    //切换当前任务
    lockTask: function(taskItem){
        var _self = this;
        console.log("lockTask in,userTaskItem",taskItem);
        //设置当前任务
        console.log("lockTask in,this",this);
        this.get("global_curStatus").setTask(taskItem);
        //同步当前任务
        var curUser = this.get("global_curStatus").getUser();
        curUser.set("currentTask",taskItem.get("task"));
        //保存到全局变量
        this.get("global_curStatus").setUser(curUser);
        //保存到服务端
        this.get("store").findRecord("userPrivate",curUser.get("id")).then(function(user){
          console.log("cur taskItem",taskItem);
          //不同角色，当前任务类型不一样
          if(curUser.get("isCustomerService")){
            user.set("currentTask",taskItem.get("task"));
          }else{
            user.set("currentTask",taskItem);
          }
          _self.controllerFor("business.mainpage").set("curTask",taskItem);
          user.save().then(function(){
            //获得当前route名称
            var currentRouteName = Ember.getOwner(_self).lookup('controller:application').currentPath;
            if(currentRouteName&&CommonUtil.Common_endsWith(currentRouteName,".index")){
              console.log("need cut .index");
              currentRouteName = currentRouteName.substr(0,currentRouteName.length-6);
            }
            var currentRouteInstance = Ember.getOwner(_self).lookup('route:' + currentRouteName);
            console.log("currentRouteName:" + currentRouteName);
            //修改全局任务数据
            _self.processTaskInfo().then(function(){
              _self.controllerFor("business.mainpage").set("curTask",_self.get("global_curStatus").getTask());
              _self.controllerFor("business.mainpage").set("otherTasks",_self.get("global_curStatus").getOtherTasks());
              if(currentRouteName==="business.mainpage.task-square"){
                return;
              }
              console.log("do refresh");
              _self.refreshTaskMenu();
              //刷新下级页面
              currentRouteInstance.refresh();
            });
          });
        });
    },
    updateAuthenticateStatus(){
      var _self = this;
      console.log('in type 3 of mianpage');
      var curUser = this.get('global_curStatus').getUser();
      var currentRouteName = Ember.getOwner(_self).lookup('controller:application').currentPath;
      if(currentRouteName&&CommonUtil.Common_endsWith(currentRouteName,".index")){
        console.log("need cut .index");
        currentRouteName = currentRouteName.substr(0,currentRouteName.length-6);
      }
      this.get('store').findRecord('user',curUser.get('id')).then(function(user){
        console.log('ininininin',_self.get('global_curStatus').getUser());
        _self.get('global_curStatus').setUser(user);
        console.log('ininininin after',_self.get('global_curStatus').getUser());
        var currentRouteInstance = Ember.getOwner(_self).lookup('route:' + currentRouteName);
        // currentRouteInstance.refresh();
      });

    },
    changePage:function(routeName,params){
      console.log("changePage:" + routeName);
      this.render('business/mainpage/' + routeName, {
        into: 'business.mainpage',
        outlet: routeName
      });
      if(params){
        //把参数直接放到目标controller中
        var targetController = App.lookup("controller:business.mainpage." + routeName);
        Object.keys(params).forEach(function(key){
          var paramKey = params[key];
          targetController.set(paramKey,params[paramKey]);
        });
      }
    },
  }
});
